﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Conqueror.API
{
    [XmlRoot("api")]
    public class APIPlayerResponse
    {
        [XmlElement("player")]
        public Player Contents { get; set; }
    }

    [XmlRoot("api")]
    public class APIMultiPlayerResponse
    {
        [XmlElement("player")]
        public List<Player> Contents { get; set; }
    }

    public enum Membership
    {
        Unknown,
        [XmlEnum("F")]
        Free,
        [XmlEnum("P")]
        Premium
    }

    public class Player
    {
        private const string mode = "player";
        public static async Task<Player> GetPlayerAsync(string username = null, int? id = null)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(GenerateURI(username, id));
            WebResponse response = await request.GetResponseAsync();

            //Error checks
            if (response.ContentType != "application/xml")
                throw new FormatException("The response is not XML");

            XmlSerializer serializer = new XmlSerializer(typeof(APIPlayerResponse));
            return await Task.Run(() => {
                var result = (APIPlayerResponse)serializer.Deserialize(response.GetResponseStream());
                return result.Contents;
            });
        }

        public static async Task<IEnumerable<Player>> GetPlayersAsync(IEnumerable<string> usernames)
        {
            string username = string.Join(",", usernames);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(GenerateURI(username));
            WebResponse response = await request.GetResponseAsync();

            //Error checks
            if (response.ContentType != "application/xml")
                throw new FormatException("The response is not XML");

            XmlSerializer serializer = new XmlSerializer(typeof(APIMultiPlayerResponse));
            return await Task.Run(() =>
            {
                var result = (APIMultiPlayerResponse)serializer.Deserialize(response.GetResponseStream());
                return result.Contents;
            });
        }

        private static Uri GenerateURI(string username = null, int? id = null)
        {
            if (!string.IsNullOrWhiteSpace(username))
                return new Uri(string.Format("{0}?mode={1}&un={2}", API.APIAddress, mode, username));
            else return new Uri(string.Format("{0}?mode={1}&u={2}", API.APIAddress, mode, id.Value));
        }

        [XmlElement("userid")]
        public string UserID { get; set; }

        [XmlElement("username")]
        public string Username { get; set; }

        [XmlElement("membership")]
        public Membership Membership { get; set; }

        [XmlElement("score")]
        public int Score { get; set; }

        [XmlElement("games_completed")]
        public int GamesCompleted { get; set; }

        [XmlElement("games_won")]
        public int GamesWon { get; set; }

        [XmlElement("rank")]
        public string Rank { get; set; }

        [XmlElement("rating")]
        public float Rating { get; set; }

        [XmlElement("country")]
        public string Country { get; set; }

        [XmlElement("attendance")]
        public float Attendance { get; set; }

        [XmlElement("medals")]
        public int Medals { get; set; }
    }
}